import permissionCheckResolveDecorate from '@kuiper/auth/dist/server/lib/permissionCheckResolveDecorate';
import errorCodesBuilder from '../../helpers/errorCodesBuilder';

const errorCodes = errorCodesBuilder('');

async function resolver(root, args, context) {
	const {
		request: {
			log,
			server: {
				app: {
					model: { Task },
				},
			},
		},
	} = context;

	const match = args.uid ? [{ $match: { uid: args.uid } }] : [];

	try {
		await Promise.all([
			Task.aggregate(
				match.concat({
					$group: {
						_id: 'warningCount',
						count: { $sum: '$result.warningCount' },
					},
				})
			),
			Task.aggregate(
				match.concat({
					$group: {
						_id: 'warningResolvedCount',
						count: { $sum: '$result.warningResolvedCount' },
					},
				})
			),
			Task.aggregate(
				match.concat({
					$group: {
						_id: 'warningUnresolvedCount',
						count: { $sum: '$result.warningUnresolvedCount' },
					},
				})
			),
			Task.aggregate(
				match.concat({
					$group: {
						_id: 'warningUnresolvedCount',
						count: { $sum: '$result.stats.subdomainCount' },
					},
				})
			),
			Task.aggregate(
				match.concat({
					$group: {
						_id: 'warningUnresolvedCount',
						count: { $sum: '$result.stats.ipCount' },
					},
				})
			),
		]);
	} catch (err) {
		const error = errorCodes['[03]更新资产信息: 更新asset记录'].from(err);
		log.error({ error }, error.rawMessage);
		throw error;
	}
}

export const resolve =
	resolver
	|> permissionCheckResolveDecorate({
		required: 'cloud-monitor\x01listAsset',
		selfOnlyArgsBuilder(
			_source,
			args,
			{
				request: {
					auth: {
						credentials: { uid },
					},
				},
			}
		) {
			args.uid = uid;
		},
	});

export default {
	resolve,
	description: '资产统计',
	type: 'AssetStatsPayload',
	args: {
		uid: 'MongoID',
	},
};
